package cn.ty.znsz.user;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.jfinal.kit.HashKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Redis;

import cn.ty.znsz.common.model.SysUser;
import cn.ty.znsz.common.model.SysUserArea;
import cn.ty.znsz.common.model.SysUserRole;

public class UserService {
	
	private SysUser userDao=new SysUser().dao();
	
	/**
	 * 用户首页分页
	 * @param paraToInt
	 * @param i
	 * @return
	 */
	public Page<Record> paginate(int pageNumber, int pageSize,String loginName,String startTime,String endTime,
			String city,String county,String town,String village,String status) {
		Page<Record> page = null;
		String querySql = "SELECT a.id,a.loginName,a.userName,a.createAt,a.`status` userStatus,c.fullName,c.id areaId,"
				+ "GROUP_CONCAT(e.id) as roleIds,GROUP_CONCAT(e.`name`) as roleNames ";
		StringBuilder sql = new StringBuilder();
		sql.append("from sys_user a LEFT JOIN sys_user_area b ON a.id=b.userId LEFT JOIN sys_area c ON b.areaId=c.id "
				+ "LEFT JOIN sys_user_role d ON a.id=d.userId LEFT JOIN sys_role e ON d.roleId=e.id WHERE 1=1 ");
		if(city != null && county == null){
			Record record=Db.findFirst("SELECT a.areaCode from sys_area a WHERE a.id=?;",city);
			sql.append(" and c.areaCode like '"+record.getStr("areaCode")+"%'");
		}
		if(county != null && town == null){
			Record record=Db.findFirst("SELECT a.areaCode from sys_area a WHERE a.id=?;",county);
			sql.append(" and c.areaCode like '"+record.getStr("areaCode")+"%'");
		}
		if(town != null && village == null){
			Record record=Db.findFirst("SELECT a.areaCode from sys_area a WHERE a.id=?;",town);
			sql.append(" and c.areaCode like '"+record.getStr("areaCode")+"%'");
		}
		if(village != null){
			Record record=Db.findFirst("SELECT a.areaCode from sys_area a WHERE a.id=?;",village);
			sql.append(" and c.areaCode like '"+record.getStr("areaCode")+"%'");
		}
		if(!"".equals(loginName) && loginName !=null){
			sql.append(" and a.loginName = '"+loginName+"'");
		}
		if(!"".equals(startTime) && startTime !=null){
			sql.append(" and a.createAt >= '"+startTime+"'");
		}
		if(!"".equals(endTime) && endTime !=null){
			sql.append(" and a.createAt <= '"+endTime+" 23:59:59'");
		}
		if(!"".equals(status) && status !=null){
			sql.append(" and a.status = "+status+"");
		}
		sql.append(" GROUP BY a.id ORDER BY a.id");
		page = Db.paginate(pageNumber, pageSize, querySql, sql.toString());		
		return page;
	}
	/**
	 * 查询菜单权限
	 * @param paraToInt
	 * @param cookie
	 * @return
	 */
	public Ret getMenuPoint(Integer menuId, String cookie) {
		String key=Redis.use().get(cookie);
		String roleIds=Redis.use().hget(key, "roleIds");
		List<Record> powers=Db.find("SELECT DISTINCT b.pointcode FROM sys_role_point a LEFT JOIN sys_menu_point b ON a.pointId=b.id "
				+ "WHERE a.roleId IN ("+roleIds+") AND b.menuId=? ORDER BY b.sortOrder;",menuId);
		return Ret.ok("操作成功").set("data", powers);
	}
	/**
	 * 保存用户
	 * @param para
	 * @param para2
	 * @param para3
	 * @param para4
	 * @param para5
	 * @return
	 */
	public Ret userSave(String loginName, String userName, String password, int areaId, String roleIds) {
		String salt = HashKit.generateSaltForSha256();
		String password2 = HashKit.sha256(salt + password);
		boolean isSuccess =Db.tx(() -> {
				SysUser user=new SysUser();
				user.setLoginName(loginName);
				user.setUserName(userName);
				user.setPassword(password2);
				user.setSalt(salt);
				user.setCreateAt(new Date());
				user.setHeadImg(PropKit.get("headImg"));
				user.use("zsql").save();
				SysUserArea sua=new SysUserArea();
				sua.setUserId(user.getId());
				sua.setAreaId(areaId);
				sua.use("zsql").save();
				String[] Ids=roleIds.split(",");
				for(String str:Ids) {
					SysUserRole sur=new SysUserRole();
					sur.setUserId(user.getId());
					sur.setRoleId(Integer.parseInt(str));
					sur.use("zsql").save();
				}
				  return true;
		});		
		if (isSuccess) {
			return Ret.ok("注册成功");
		} else {
			return Ret.fail("注册失败");
		}
		
	}
	/**
	 * 编辑用户保存
	 * @param para
	 * @param paraToInt
	 * @param para2
	 * @param paraToInt2
	 * @return
	 */
	public Ret userUpdate(String userName, Integer areaId, String roleIds, Integer id) {
		boolean isSuccess =Db.tx(() -> {
				Db.use("zsql").update("UPDATE sys_user SET userName=? WHERE id=?",userName,id);
				Db.use("zsql").update("UPDATE sys_user_area SET areaId=? WHERE userId=?",areaId,id);
				Db.use("zsql").update("DELETE from sys_user_role WHERE userId=?",id);
				String[] Ids=roleIds.split(",");
				for(String str:Ids) {
					SysUserRole sur=new SysUserRole();
					sur.setUserId(id);
					sur.setRoleId(Integer.parseInt(str));
					sur.use("zsql").save();
				}
				  return true;
		});		
		if (isSuccess) {
			return Ret.ok("操作成功");
		} else {
			return Ret.fail("操作失败");
		}
	}
	/**
	 * 删除用户
	 * @param paraToInt
	 * @param paraToInt2
	 * @return
	 */
	public Ret userUpdate(Integer id, Integer userStatus) {
		int flag=userStatus==1?0:1;
		Db.use("zsql").update("update sys_user SET `status`=? WHERE id=?;",flag,id);
		return Ret.ok("操作成功");
	}
	/**
	 * 重置密码
	 * @param paraToInt
	 * @return
	 */
	public Ret userResetPwd(Integer id) {
		String defaultpass=PropKit.get("defaultpass");
		SysUser user=userDao.findById(id);
		String password = HashKit.sha256(user.getSalt() + defaultpass);
		Db.use("zsql").update("update sys_user SET `password`=? WHERE id=?;",password,id);
		return Ret.ok("操作成功");
	}
	/**
	 * 判断用户是否有编辑删除重置密码权限
	 * @param para
	 * @return
	 */
	public Ret checkRolePower(String roleIds,String cookie) {
		String key=Redis.use().get(cookie);
		String myRoleIds=Redis.use().hget(key, "roleIds");//用户的角色
		String childRoleIds=Db.queryStr("SELECT GROUP_CONCAT(a.childIds) roles from sys_role a WHERE a.id IN ("+myRoleIds+");");
		String childRoleIds2=Db.queryStr("SELECT GROUP_CONCAT(a.childIds) roles from sys_role a WHERE a.id IN ("+roleIds+");");
		String[] roles1=childRoleIds.split(",");
		Set<String> parentSet=new HashSet<>();
		for(String str:roles1) {
			parentSet.add(str);
		}
		String[] roles2=childRoleIds2.split(",");
		Set<String> childSet =new HashSet<>();
		for(String str:roles2) {
			childSet.add(str);
		}
		if (parentSet.containsAll(childSet)) {
			return Ret.ok();
        } else {
            return Ret.fail("无权限进行此操作");
        }				
	}		
}
